/**
 * Book.js 为每一个竖排的簿记组件
 */
import React, { PureComponent } from 'react';
import _ from 'lodash';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message } from 'antd';
import { SelectC } from '../../../../comps';
import { connect } from 'dva';
import TopButtonC from './TopButtonC';
import BookVanilla from './BookVanilla';
import BaseOption from './BaseOption';
import BookBarrier from './BookBarrier';
import BookDual from './BookDual';
import BookSnowball from './bookSnowball';
@Form.create()
@connect(({ shareOptionManageM, bookM, globalM }) => ({ shareOptionManageM, bookM, globalM }))
export default class Book extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      dataSource: this.props.dataSource,
      isShow: false, // 选择了期权结构则为true，按钮点亮 表单出来
      structure: '', //期权结构
      initialPrice: undefined, //期初价格
      isLoading: false,
      beginDate: '',
      endDate: '',
    };
  }
  componentDidMount() {
    const { dataSource } = this.props;
    // 复用和编辑的时候回填期权结构
    this.setState(
      {
        structure: dataSource.structure,
        isShow: dataSource.structure ? true : false,
        initialPrice: dataSource.info[0].bookMain.initialPrice,
      },
      () => this.structChangeAuto(this.state.structure),
    );
  }
  // 保存
  save = () => {
    const {
      dataSource,
      dispatch,
      bookM: { mapData },
    } = this.props;
    const { structure } = this.state;
    const bookMain = this.$BaseOption.getSettingInfo();
    let num = undefined;
    mapData.forEach((ele, index) => {
      if (ele.key === dataSource.key) {
        num = index;
        return false;
      }
    });
    if (!bookMain) {
      message.error('基础期权信息填写不规范');
      return false;
    }
    const bookVanilla = this.$BookVanilla.getSettingInfo();
    if (!bookVanilla) {
      message.error('香草期权信息填写不规范');
      return false;
    }
    const bookBarrier = this.$BookBarrier.getSettingInfo();
    if (!bookBarrier) {
      message.error('障碍期权信息填写不规范');
      return false;
    }
    const bookDual = this.$BookDual.getSettingInfo();
    if (!bookDual) {
      message.error('二元期权信息填写不规范');
      return false;
    }
    let bookSnowball;
    if (structure == '4') {
      bookSnowball = this.$bookSnowball.getSettingInfo();
      if (!bookSnowball) {
        message.error('雪球期权信息填写不规范');
        return false;
      }
    }

    let vo = {
      structure,
      info: [
        {
          bookMain,
          bookVanilla: structure === '1' ? bookVanilla : null,
          bookBarrier: structure === '2' ? bookBarrier : null,
          bookDual: structure === '3' ? bookDual : null,
          bookSnowball: structure === '4' ? bookSnowball : null,
        },
      ],
    };
    this.setState({ isLoading: true });
    if (dataSource.bundleId && dataSource.bundleId !== '') {
      // 更新
      let _info = dataSource.info;
      vo.info[0].bookMain = { ..._info[0].bookMain, ...vo.info[0].bookMain };
      vo.info[0].bookVanilla = vo.info[0].bookVanilla ? { ..._info[0].bookVanilla, ...vo.info[0].bookVanilla } : null;
      vo.info[0].bookBarrier = vo.info[0].bookBarrier ? { ..._info[0].bookBarrier, ...vo.info[0].bookBarrier } : null;
      vo.info[0].bookDual = vo.info[0].bookDual ? { ..._info[0].bookDual, ...vo.info[0].bookDual } : null;
      vo.info[0].bookSnowball = vo.info[0].bookSnowball ? { ..._info[0].bookSnowball, ...vo.info[0].bookSnowball } : null;
      dispatch({
        type: 'bookM/upDataOneBook',
        payload: {
          bundleId: dataSource.bundleId,
          ...vo,
        },
        callback: (status, data) => {
          if (status === 'success') {
            message.success('更新成功');
            dispatch({
              type: 'bookM/save',
              payload: {
                pageIsChange: true,
              },
            });
          }
          this.setState({ isLoading: false });
        },
      });
    } else {
      //新增
      dispatch({
        type: 'bookM/saveOneBook',
        payload: vo,
        callback: (status, data) => {
          if (status === 'success') {
            message.success('保存成功');
            let newMapData = _.cloneDeep(mapData);
            let _dataSource = { ...dataSource, ...vo };
            if (data && data.bundleId && data.bookId) {
              _dataSource.bundleId = data.bundleId;
              _dataSource.info[0].bookMain.bookId = data.bookId;
              newMapData.splice(num, 1, _dataSource);
              newMapData[0].info[0].bookMain.tradingCode = newMapData[0].info[0].bookMain.tradingCode.split('-')[1];
            }
            dispatch({
              type: 'bookM/save',
              payload: {
                pageIsChange: true,
                mapData: newMapData,
              },
            });
          }
          this.setState({ isLoading: false });
        },
      });
    }
  };
  // 删除
  delete = () => {
    const {
      bookM: { mapData },
      dispatch,
      dataSource,
    } = this.props;
    // 本地删除
    let data = _.cloneDeep(mapData);
    const newData = data.filter((ele) => {
      return ele.key !== dataSource.key;
    });
    dispatch({
      type: 'bookM/save',
      payload: { mapData: newData },
    });
    // 线上删除
    if (dataSource.bundleId && dataSource.bundleId !== '') {
      dispatch({
        type: 'shareOptionManageM/deleteOptionByBookId',
        payload: { bundleId: dataSource.bundleId },
        callback: (status) => {
          if (status === 'success') {
            message.success('删除成功');
            dispatch({
              type: 'bookM/save',
              payload: {
                pageIsChange: true,
              },
            });
          }
        },
      });
    }
  };
  // 试算
  account = () => {
    message.success('簿记执行试算');
  };

  structChangeAuto = (e) => {
    const {
      bookM: { titleOpen },
      dispatch,
    } = this.props;
    if (e) {
      let type;
      e == '4' ? (type = +e + 3) : (type = +e + 1);
      dispatch({
        type: 'bookM/changeOpenStatus',
        payload: {
          ['isOpen' + type]: !titleOpen['isOpen' + type],
        },
      });
    }
  };
  // 期权结构变化
  structChange = (e) => {
    const {
      form: { setFieldsValue },
      bookM: { titleOpen },
      dispatch,
    } = this.props;
    if (e) {
      let type;
      e == '4' ? (type = +e + 3) : (type = +e + 1);
      dispatch({
        type: 'bookM/changeOpenStatus',
        payload: {
          ['isOpen' + type]: !titleOpen['isOpen' + type],
        },
      });
    }

    this.setState(
      {
        isShow: true,
        structure: e,
      },
      () => {
        // 带出期权结构
        this.$BaseOption.structureChange(e);
        // 对各个组件的form表单清空
        // this.$BaseOption.resetForm()
        this.$BookBarrier.resetForm();
        this.$BookDual.resetForm();
        this.$BookVanilla.resetForm();
        this.$bookSnowball.resetForm();
      },
    );
  };
  // baseOption中期权价格改变导致 障碍组件和二元组件中障碍价格和触碰价格重置
  onInitialPriceChange = (e) => {
    const { structure } = this.state;
    if (structure == '2') {
      // 障碍组件
      this.$BookBarrier.resetBarrier();
    }
    if (structure == '3') {
      // 二元组件
      this.$BookDual.resetTrigger();
    }
    if (structure == '4') {
      // 雪球
      this.$bookSnowball.resetTrigger(e);
    }
    this.setState({
      initialPrice: e,
    });
  };

  beginDate = (e) => {
    this.setState({ beginDate: e ? e : '' });
  };
  endDate = (e) => {
    this.setState({ endDate: e ? e : '' });
  };

  render() {
    const { isShow, structure, isLoading } = this.state;
    const {
      dataSource,
      form: { getFieldDecorator },
      bookM: { titleOpen, onlyView },
      type,
      globalM: { dataDictionary: dictionary },
    } = this.props;
    const btnProps2 = {
      isShowCalc: isShow,
      isShowSave: isShow,
      isShowDelete: true,
      isLoading: isLoading,
      onSave: this.save,
      onDelete: this.delete,
      onCalc: this.account,
    };

    const ds1 = dictionary['OTC_OPTION_BOOK_OPTIONSTRUCT']
      ? dictionary['OTC_OPTION_BOOK_OPTIONSTRUCT'].map((ele) => {
          return { title: ele.value, value: ele.code };
        })
      : [];
    // 编辑的时候禁止期权结构的修改
    const ds2 = type == '2' || type == '3' ? true : false;
    return (
      <div className='book'>
        {onlyView ? (
          <div style={{ height: '33px', paddingRight: '20px' }}></div>
        ) : (
          <div style={{ height: '33px', paddingRight: '20px' }}>
            <TopButtonC {...btnProps2} />
          </div>
        )}
        <div className='formDiv'>
          {/* 期权结构 */}
          <div style={{ height: '39px', marginBottom: '10px' }}>
            <SelectC
              dataIndex='structure'
              form={this.props.form}
              dataSource={ds1}
              disabled={ds2 || onlyView}
              initialValue={dataSource.structure}
              onChange={this.structChange}
              style={{ width: '100%', height: '39px' }}
            />
          </div>
          <div style={{ height: isShow ? 'auto' : '0px', overflow: 'hidden' }}>
            {/* 基础期权信息 */}
            <div>
              <BaseOption
                bookMain={dataSource.info[0].bookMain}
                structure={structure}
                onRef={(ref) => {
                  this.$BaseOption = ref;
                }}
                onInitialPriceChange={this.onInitialPriceChange}
                type={type}
                beginDate={this.beginDate}
                endDate={this.endDate}
              />
            </div>
            {/* 香草 */}
            {/* 留下与标题等高的空格 */}
            <div style={{ height: '49px' }}></div>
            <div style={{ height: titleOpen.isOpen2 ? 'auto' : '0px', overflow: 'hidden' }}>
              <BookVanilla
                bookVanilla={dataSource.info[0].bookVanilla || {}}
                structure={structure}
                onRef={(ref) => {
                  this.$BookVanilla = ref;
                }}
              />
            </div>
            {/* 障碍 */}
            {/* 留下与标题等高的空格 */}
            <div style={{ height: '49px' }}></div>
            <div style={{ height: titleOpen.isOpen3 ? 'auto' : '0px', overflow: 'hidden' }}>
              <BookBarrier
                bookBarrier={dataSource.info[0].bookBarrier || {}}
                structure={structure}
                onRef={(ref) => {
                  this.$BookBarrier = ref;
                }}
                initialPrice={this.state.initialPrice}
                beginDate={this.state.beginDate}
                endDate={this.state.endDate}
              />
            </div>
            {/* 二元 */}
            {/* 留下与标题等高的空格 */}
            <div style={{ height: '49px' }}></div>
            <div style={{ height: titleOpen.isOpen4 ? 'auto' : '0px', overflow: 'hidden' }}>
              <BookDual
                bookDual={dataSource.info[0].bookDual || {}}
                structure={structure}
                onRef={(ref) => {
                  this.$BookDual = ref;
                }}
                initialPrice={this.state.initialPrice}
                type={type}
                beginDate={this.state.beginDate}
                endDate={this.state.endDate}
              />
            </div>
            {/* 雪球 */}
            {/* 留下与标题等高的空格 */}
            <div style={{ height: '49px' }}></div>
            <div style={{ height: titleOpen.isOpen7 ? 'auto' : '0px', overflow: 'hidden' }}>
              <BookSnowball
                bookSnowball={dataSource.info[0].bookSnowball || {}}
                structure={structure}
                onRef={(ref) => {
                  this.$bookSnowball = ref;
                }}
                initialPrice={this.state.initialPrice}
                beginDate={this.state.beginDate}
                endDate={this.state.endDate}
              />
            </div>
          </div>
        </div>
      </div>
    );
  }
}
